import { View, Text, Button, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { getCurrentEnv } from '../../utils/payment';
import './index.scss';

// 订单接口
interface Order {
  id: number;
  orderNo: string;
  customerName: string;
  customerPhone: string;
  totalAmount: number;
  status: string;
  paymentMethod: string;
  createTime: string;
  products: Array<{
    name: string;
    quantity: number;
    price: number;
  }>;
}

export default function OrderList() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('all'); // all, pending, paid, processing, completed, cancelled

  useEffect(() => {
    loadOrderList();
  }, [activeTab]);

  const loadOrderList = async () => {
    try {
      setLoading(true);
      
      if (getCurrentEnv() === 'development') {
        // 开发环境：使用模拟数据
        const mockOrders = generateMockOrders();
        const filteredOrders = filterOrdersByStatus(mockOrders, activeTab);
        setOrders(filteredOrders);
        console.log('🎯 [开发环境] 使用模拟订单列表:', filteredOrders);
      } else {
        // 生产环境：调用真实API
        const { getOrders } = await import('../../api/order');
        const response = await getOrders(1, 20, activeTab === 'all' ? undefined : activeTab);
        if (response.isSuccess) {
          setOrders(response.data);
        }
      }
    } catch (error) {
      console.error('获取订单列表失败:', error);
      Taro.showToast({
        title: '获取订单列表失败',
        icon: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  // 生成模拟订单数据
  const generateMockOrders = (): Order[] => {
    const statuses = ['pending', 'paid', 'processing', 'completed', 'cancelled'];
    const products = [
      { name: '寿衣', price: 1680 },
      { name: '玉石骨灰盒', price: 2999 },
      { name: '白菊花束', price: 299 },
      { name: '纸扎祭品', price: 899 },
      { name: '悼念花圈', price: 1299 }
    ];

    return Array.from({ length: 8 }, (_, index) => ({
      id: index + 1,
      orderNo: `ORD2024${String(new Date().getMonth() + 1).padStart(2, '0')}${String(index + 1).padStart(3, '0')}`,
      customerName: '测试用户',
      customerPhone: '13800138000',
      totalAmount: products[index % products.length].price,
      status: statuses[index % statuses.length],
      paymentMethod: '微信支付',
      createTime: new Date(Date.now() - index * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
      products: [
        {
          name: products[index % products.length].name,
          quantity: 1,
          price: products[index % products.length].price
        }
      ]
    }));
  };

  // 根据状态过滤订单
  const filterOrdersByStatus = (orders: Order[], status: string): Order[] => {
    if (status === 'all') return orders;
    return orders.filter(order => order.status === status);
  };

  // 获取状态文本
  const getStatusText = (status: string): string => {
    const statusMap: Record<string, string> = {
      pending: '待支付',
      paid: '已支付',
      processing: '处理中',
      completed: '已完成',
      cancelled: '已取消'
    };
    return statusMap[status] || status;
  };

  // 获取状态样式类
  const getStatusClass = (status: string): string => {
    const classMap: Record<string, string> = {
      pending: 'status-pending',
      paid: 'status-paid',
      processing: 'status-processing',
      completed: 'status-completed',
      cancelled: 'status-cancelled'
    };
    return classMap[status] || '';
  };

  // 处理订单点击
  const handleOrderClick = (orderId: number) => {
    Taro.navigateTo({
      url: `/pages/order-detail/index?orderId=${orderId}`
    });
  };

  // 处理订单操作
  const handleOrderAction = (order: Order, action: string) => {
    switch (action) {
      case 'pay':
        Taro.showToast({
          title: '跳转支付...',
          icon: 'loading'
        });
        break;
      case 'cancel':
        Taro.showModal({
          title: '确认取消',
          content: '确定要取消这个订单吗？',
          success: (res) => {
            if (res.confirm) {
              Taro.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              // 更新订单状态
              setOrders(prev => prev.map(o => 
                o.id === order.id ? { ...o, status: 'cancelled' } : o
              ));
            }
          }
        });
        break;
      case 'delete':
        Taro.showModal({
          title: '确认删除',
          content: '确定要删除这个订单吗？',
          success: (res) => {
            if (res.confirm) {
              Taro.showToast({
                title: '订单已删除',
                icon: 'success'
              });
              // 删除订单
              setOrders(prev => prev.filter(o => o.id !== order.id));
            }
          }
        });
        break;
    }
  };

  // 获取订单操作按钮
  const getOrderActions = (order: Order) => {
    switch (order.status) {
      case 'pending':
        return (
          <View className='order-actions'>
            <Button 
              size='mini' 
              className='action-btn cancel-btn'
              onClick={(e) => {
                e.stopPropagation();
                handleOrderAction(order, 'cancel');
              }}
            >
              取消订单
            </Button>
            <Button 
              size='mini' 
              type='primary' 
              className='action-btn pay-btn'
              onClick={(e) => {
                e.stopPropagation();
                handleOrderAction(order, 'pay');
              }}
            >
              立即支付
            </Button>
          </View>
        );
      case 'cancelled':
        return (
          <View className='order-actions'>
            <Button 
              size='mini' 
              className='action-btn delete-btn'
              onClick={(e) => {
                e.stopPropagation();
                handleOrderAction(order, 'delete');
              }}
            >
              删除订单
            </Button>
          </View>
        );
      default:
        return null;
    }
  };

  const tabs = [
    { key: 'all', label: '全部' },
    { key: 'pending', label: '待支付' },
    { key: 'paid', label: '已支付' },
    { key: 'processing', label: '处理中' },
    { key: 'completed', label: '已完成' },
    { key: 'cancelled', label: '已取消' }
  ];

  return (
    <View className='order-list-container'>
      {/* 状态筛选标签 */}
      <View className='status-tabs'>
        <ScrollView scrollX className='tabs-scroll'>
          <View className='tabs-wrapper'>
            {tabs.map(tab => (
              <View
                key={tab.key}
                className={`tab-item ${activeTab === tab.key ? 'active' : ''}`}
                onClick={() => setActiveTab(tab.key)}
              >
                <Text className='tab-text'>{tab.label}</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      </View>

      {/* 订单列表 */}
      <ScrollView scrollY className='order-scroll'>
        {loading ? (
          <View className='loading-container'>
            <Text>加载中...</Text>
          </View>
        ) : orders.length > 0 ? (
          <View className='order-content'>
            {orders.map(order => (
              <View
                key={order.id}
                className='order-item'
                onClick={() => handleOrderClick(order.id)}
              >
                {/* 订单头部 */}
                <View className='order-header'>
                  <View className='order-info'>
                    <Text className='order-no'>订单号：{order.orderNo}</Text>
                    <Text className='order-time'>{order.createTime}</Text>
                  </View>
                  <Text className={`order-status ${getStatusClass(order.status)}`}>
                    {getStatusText(order.status)}
                  </Text>
                </View>

                {/* 商品信息 */}
                <View className='order-products'>
                  {order.products.map((product, index) => (
                    <View key={index} className='product-item'>
                      <View className='product-info'>
                        <Text className='product-name'>{product.name}</Text>
                        <Text className='product-spec'>数量：{product.quantity}</Text>
                      </View>
                      <Text className='product-price'>¥{product.price}</Text>
                    </View>
                  ))}
                </View>

                {/* 订单总价 */}
                <View className='order-footer'>
                  <View className='total-info'>
                    <Text className='total-label'>共{order.products.length}件商品</Text>
                    <Text className='total-amount'>合计：¥{order.totalAmount}</Text>
                  </View>
                  {getOrderActions(order)}
                </View>
              </View>
            ))}
          </View>
        ) : (
          <View className='empty-container'>
            <Text className='empty-text'>暂无订单</Text>
            <Text className='empty-desc'>去选购一些商品吧</Text>
          </View>
        )}
      </ScrollView>
    </View>
  );
}
